# view/login_window.py
import customtkinter as ctk
from utils.utils import logger, get_current_version
from view.register_window import RegisterWindow
import json
from pathlib import Path
from utils.security import verify_password
from view.main_gui import MainGUI


def validate_login(username: str, password: str) -> bool:
    """从本地 users.json 验证用户（使用 bcrypt 哈希）"""
    users_file = Path(__file__).parent.parent / "data" / "users.json"
    if not users_file.exists():
        return False
    try:
        with open(users_file, "r", encoding="utf-8") as f:
            users = json.load(f)
        user = users.get(username)
        if not user:
            return False
        stored_hash = user.get("password_hash")
        if not stored_hash:
            return False
        return verify_password(password, stored_hash)
    except Exception as e:
        from utils.utils import logger
        logger.error(f"登录验证异常: {e}")
        return False


class LoginWindow(ctk.CTk):
    def __init__(self):
        super().__init__()
        self.title("用户登录")
        self.geometry("400x300")
        self.resizable(False, False)
        self.current_version = get_current_version()

        # 标题
        title_label = ctk.CTkLabel(
            self,
            text="电商数据采集工具",
            font=("Microsoft YaHei", 18, "bold")
        )
        title_label.pack(pady=(20, 15))

        # 表单区域（使用 grid 布局，更精确控制间距）
        form_frame = ctk.CTkFrame(self, fg_color="transparent")
        form_frame.pack(pady=10)

        # 第一行：用户名
        ctk.CTkLabel(form_frame, text="用户名：", anchor="w", width=60).grid(row=0, column=0, padx=(10, 5), pady=4, sticky="w")
        self.username_entry = ctk.CTkEntry(form_frame, placeholder_text="请输入用户名", width=220)
        self.username_entry.grid(row=0, column=1, padx=(0, 10), pady=4)

        # 第二行：密码
        ctk.CTkLabel(form_frame, text="密  码：", anchor="w", width=60).grid(row=1, column=0, padx=(10, 5), pady=4, sticky="w")
        self.password_entry = ctk.CTkEntry(form_frame, placeholder_text="请输入密码", show="*", width=220)
        self.password_entry.grid(row=1, column=1, padx=(0, 10), pady=4)

        # 按钮区域
        button_frame = ctk.CTkFrame(self, fg_color="transparent")
        button_frame.pack(pady=15)

        login_btn = ctk.CTkButton(button_frame, text="登录", command=self.attempt_login, width=100, height=32)
        login_btn.pack(side="left", padx=(0, 10))

        register_btn = ctk.CTkButton(button_frame, text="注册", command=self.open_register, width=100, height=32, fg_color="gray70", hover_color="gray60")
        register_btn.pack(side="left")

        # 绑定回车键
        self.password_entry.bind("<Return>", lambda event: self.attempt_login())

        # 版本号
        version_label = ctk.CTkLabel(
            self,
            text=f"当前版本：{self.current_version}",
            font=("Microsoft YaHei", 10),
            text_color="gray"
        )
        version_label.pack(side="bottom", pady=10)

    def attempt_login(self):
        if getattr(self, '_login_in_progress', False):
            return
        self._login_in_progress = True
        username = self.username_entry.get().strip()
        password = self.password_entry.get().strip()
        if not username or not password:
            self.show_error("用户名和密码不能为空！")
            return
        if validate_login(username, password):
            logger.info(f"用户 {username} 登录成功")
            self.destroy()
            # 启动新的主界面窗口
            main_app = MainGUI()
            main_app.mainloop()
        else:
            self._login_in_progress = False
            self.show_error("用户名或密码错误！")

    def show_error(self, message: str):
        error_win = ctk.CTkToplevel(self)
        error_win.title("登录失败")
        error_win.geometry("260x100")
        error_win.resizable(False, False)
        error_win.grab_set()
        ctk.CTkLabel(error_win, text=message, text_color="red", wraplength=240).pack(pady=20)
        ctk.CTkButton(error_win, text="确定", command=error_win.destroy, width=80).pack()

    def open_register(self):
        RegisterWindow(self)